import java.util.Map;

public class CreateTreeInAndPre {
    public Map<Integer,Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length != inorder.length){
            return null;
        }
        int n = inorder.length;
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i],i);
        }
        return myBuildTree(preorder,inorder,0,n-1,0,n-1);
    }

    private TreeNode myBuildTree(int[] preorder, int[] inorder, int preBegin, int preEnd, int inBegin, int inEnd) {
        if(preBegin > preEnd||inBegin>inEnd){
            return null;
        }
        TreeNode root = new TreeNode(preorder[preBegin]);
        //得到根节点在中序遍历的下标
        int inRoot = map.get(root.val);
        //根据中序序列得到当前根节点的左子树的个数
        int leftNum = inRoot - inBegin;
        root.left = myBuildTree(preorder,inorder,preBegin + 1,preBegin+leftNum,inBegin,inRoot-1);
        root.right = myBuildTree(preorder,inorder,preBegin+leftNum+1,preEnd,inRoot+1,inEnd);
        return root;
    }
}
